# kb_loader.py
import os
import re

KB = {}  # 全局知识字典

def load_kb():
    """一次性把 knowledge_base 里所有 txt 读进内存"""
    base_path = os.path.join(os.path.dirname(__file__), 'knowledge_base')
    for fn in os.listdir(base_path):
        if not fn.endswith('.txt'):
            continue
        with open(os.path.join(base_path, fn), encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                try:
                    q, a = line.split('|', 1)
                    KB[q.lower().strip()] = a.strip()
                except ValueError:
                    continue

def search_kb(query: str, topk=3):
    """简单关键词匹配，返回前 topk 条答案"""
    query_l = query.lower()
    return [a for q, a in KB.items() if q in query_l][:topk]

# 启动时自动加载
load_kb()